//
//  WBMainViewController.swift
//  SwiftWeibo
//
//  Created by Lausen on 2017/4/7.
//  Copyright © 2017年 id. All rights reserved.
//

import UIKit
import SVProgressHUD
/// 这个就是TabbarController
class WBMainViewController: UITabBarController {

    fileprivate var time: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildrenControllers()
        setupComposeButton()
        
        setupTimer()
        
        addNewfeaturView()
        
        //设置代理
        delegate = self
        
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin(notification:)), name: NSNotification.Name(rawValue: WBUserLogonNotification), object: nil)
    }
    
    @objc private func userLogin(notification:Notification){
        
        var when  = DispatchTime.now()
        
        if notification.object != nil{
            
            /// 设置显示状态为渐变的
            SVProgressHUD.showInfo(withStatus: "登录状态过期,请重新登录")
            SVProgressHUD.setDefaultMaskType(.gradient)
            
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
        
            let nav = UINavigationController(rootViewController: WBOAuthController())
            
            self.present(nav, animated: true, completion: nil)
        }
    }
    
    deinit {
        
        //销毁时钟
        time?.invalidate()
        
        NotificationCenter.default.removeObserver(self)
    }
    
    //由方法改为了计算性属性了
    /**
     portrait: 竖屏.肖像
     landspace:横屏,风景画
     
     --使用代码控制横竖屏的好处,可以在需要横屏的时候,单独处理
     --重写了这个属性之后,当前控制器及其子控制器都会遵守这个横竖屏了
     --如果播放视屏,通常是通过model展现的
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        
        return .portrait
    }
    
    //MARK -- 按钮的监听方法
    /// fileprivate 能够保证只有当前文件能访问这个方法,@objc允许这个方法在运行时通过,OC的消息机制被调用
    @objc fileprivate func composeStatus(){ //现在的private是当前文件的分类也调用不到了,所以要用到fileprivate表明文件内私密的,这个fileprivate的级别没有private的私密级别高,
    
        let composeView = WBComposeView.composeView()
        
        composeView.show {[weak composeView] (clsName: String?) in
            
            guard let clsName = clsName else{
                
                composeView?.removeFromSuperview()
                
                return
            }
            
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as! UIViewController.Type
            let vc = cls.init()
            
            let naviVC = UINavigationController(rootViewController: vc)
            
            self.present(naviVC, animated: true, completion: {
                
                composeView?.removeFromSuperview()
            })
        }
    }
    
    lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
}


extension WBMainViewController{
    
    fileprivate func addNewfeaturView(){
    
        //0:根据用户是否登录来判断是否要加载
        if !WBNetworkManager.shared.userLogon {
            
            return
        }
        
        //1:根据是不是新版本来判断加载哪种视图
        let v = isNewVersion ? WBNewfeatureView.newFeatureView() : WBWelcomeView.welcomeView()
        
        view.addSubview(v)
    }
    
    private var isNewVersion: Bool{
        
        //1:取plist里面的版本号
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        
        //2:取本地保存的版本号
        let path: String = ("version" as NSString).cz_appendDocumentDir()
        let sandBoxVersion = try? String(contentsOfFile: path)
        
        //3:如果不同就替换掉本地的
        try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        //4:返回是新的版本,否则返回不是新版本
        return currentVersion != sandBoxVersion
    }
}



// MARK: - UITabBarControllerDelegate
extension WBMainViewController: UITabBarControllerDelegate{

    /// 将要切换控制器的时候,调用到方法
    ///
    /// - Parameters:
    ///   - tabBarController: 当前的tabBarController
    ///   - viewController: 将要切换的控制器
    /// - Returns: 是否切换
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {

        /// 将要跳转控制器的缩影
        let idx = (childViewControllers as Array).index(of: viewController)
        
        if selectedIndex == 0 && idx == selectedIndex{
            
            let navi = viewControllers?[0] as! UINavigationController
            
            let vc = navi.viewControllers[0] as! WBHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x: 0,y: -64), animated: true)
//            vc.tableView?.scrollsToTop = true

            let index = IndexPath(row: 0, section: 0)

            vc.tableView?.scrollToRow(at: index, at: .top, animated: true)
            
// MARK: - 滚动到头部之后,刷新数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                
                vc.loadData()
            })
        }
        
        //清楚tabBarItem/appIcon上面的数字
        tabBarController.tabBar.items?.first?.badgeValue = nil
        UIApplication.shared.applicationIconBadgeNumber = 0
        
        //如果是UIViewController对象,就不要切换,这样就避免了,点击容错点的时候,这个应用程序显示了一个隐藏了的控制器
        return !viewController.isMember(of: UIViewController.self)
    }
}

// MARK: - 用来做设置时钟,并且显示角标
extension WBMainViewController{
    
    //实例化一个时钟
    fileprivate func setupTimer() {
        
        time = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
    }
    
    
    @objc private func updateTime(){
        
        if !WBNetworkManager.shared.userLogon {
            
            return
        }
        
        WBNetworkManager.shared.unreadCount { (count) in
            
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            /// 显示应用程序的角标,
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

/**
 1:extension类似于OC中的分类,在Swift中还可以用来切换代码块
 2:可以把相近功能的函数,放在一个Extension中
 3:便于代码的维护
 4:注意:和OC中的分类一样,Extension中不能定义属性
 */
// MARK: - 设置主界面
extension WBMainViewController{
    
    fileprivate func setupComposeButton(){
        
        tabBar.addSubview(composeButton)
        
        let count = CGFloat(childViewControllers.count)
        
        //tabbar的两个按钮之间都会有一个像素的容错点,处理这个用tabBar的代理就可以了
        let w = tabBar.bounds.width / count
        
        //insetBy 相当于OC里面的CGRectInset ,正数向里缩进,负数向外扩展,所以很多往tabbar外面漏出来的按钮就是靠dy来控制的
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy:0)
        
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    fileprivate func setupChildrenControllers(){
        
        //1:加载沙盒中的路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        var data = NSData(contentsOfFile: jsonPath)
        
        //如果沙盒里面的数据位nil那么就加载本地的数据
        if data == nil {
            
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            
            data = NSData(contentsOfFile: path!)
        }
        
        
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:Any]]
            else{
        
                return
        }
        
        
//        let array = [
//            ["clsName":"WBHomeViewController","title":"首页","imageName":"tabbar_home",
//             "vistorInfo":["imageName":"","message":"关注一些人,回这里看看有什么惊喜,关注一些人,回这里看看有什么惊喜"]
//             ],
//            ["clsName":"WBMessageViewController","title":"消息","imageName":"tabbar_message_center",
//             "vistorInfo":["imageName":"visitordiscover_image_message","message":"登录后,别人评论你的微博,发给你的消息,都会在这里收到通知"]
//             ],
//            ["clsName":"UIViewController"],
//            ["clsName":"WBDiscoverViewController","title":"发现","imageName":"tabbar_discover",
//             "vistorInfo":["imageName":"","message":"登录后,最新最热的微博尽在掌握,不会与时事潮流擦肩而过"]
//             ],
//            ["clsName":"WBProfileViewController","title":"我的","imageName":"tabbar_profile",
//             "vistorInfo":["imageName":"visitordiscover_image_profile","message":"登录后,你的个人信息,会在这里显示"]
//             ],
//        ]
//        
//       
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        
//        (data as NSData).write(toFile: "/Users/lausen/Desktop/demo.json", atomically: true)
        
        var arrayM = [UIViewController]()
        
        for dict in array! {
            
            arrayM.append(controller(dict: dict))
        }
        
        viewControllers = arrayM
    }
    
    //利用字典来创建控制器
    /// <#Description#>
    ///
    /// - Parameter dict: ["clsName":"","title":"","imageName":""]
    /// - Returns: 返回的都是由导航控制器包裹的控制器
    private func controller(dict:[String:Any]) -> UIViewController{
        
        guard let clsName = dict["clsName"] as? String,
              let title = dict["title"] as? String,
              let imageName = dict["imageName"] as? String,
              let vistorInfo = dict["vistorInfo"] as? [String:String],
              let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type
            else {
                
                return UIViewController()
        }
        
        let vc = cls.init()
        
        vc.title = title
        
        //设置图像
        vc.tabBarItem.image = UIImage(named: imageName)?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        //设置tabBar的标题颜色
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.gray], for: .normal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        
        //这儿修改tabbar字体的大小, 系统默认的是12号字, Xcode8.2中设置normal或者highlighted模式下的字体都有用了
//        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 20)], for: .normal)
        
        vc.vistorInfoDictionary = vistorInfo
        
        ///这个方法,会调用一次pushViewController,将控制器进行压栈,放在栈低去了
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
    }
    
}
